package com.sf.sgs.mark.exception.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.sf.sgs.mark.exception.common.constant.KafkaConstants;
import com.sf.sgs.mark.exception.common.utils.DateUtils;
import com.sf.sgs.mark.exception.domain.KafkaData;
import com.sf.sgs.mark.exception.dto.DeliveryChangeDto;
import com.sf.sgs.mark.exception.dto.oms.delivery.DeliveryOmsRequestDto;
import com.sf.sgs.mark.exception.dto.oms.delivery.sub.ActionDto;
import com.sf.sgs.mark.exception.dto.oms.delivery.sub.DestinationInfoDto;
import com.sf.sgs.mark.exception.dto.oms.delivery.sub.SpecialHandlerDto;
import com.sf.sgs.mark.exception.dto.oms.delivery.sub.WaybillDto;
import com.sf.sgs.mark.exception.json.JsonCoder;
import com.sf.sgs.mark.exception.json.MdmtrmJsonFeature;
import com.sf.sgs.mark.exception.service.IKafkaDataService;

@Controller
@RequestMapping("/customer")
public class CustomerContoller {

	private static final String TXID_PREFIX = "00400000000000";
	@Autowired
	private IKafkaDataService kafkaDataService;
	
	protected JsonCoder jsonCoder = new JsonCoder(MdmtrmJsonFeature.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

	@RequestMapping(value = "/sendDeliveryChangeData", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addDeliveryChange(DeliveryChangeDto deliveryChangeDto) {
		Map<String, Object> map = new HashMap<>();
		try {
			DeliveryOmsRequestDto dto = new DeliveryOmsRequestDto();
			Random random = new Random();
			dto.setTxid(TXID_PREFIX + deliveryChangeDto.getWaybillNo() + random.nextInt(10));
			dto.setTimestamp(new Date().getTime());
			WaybillDto waybill = new WaybillDto();
			waybill.setMainNo(deliveryChangeDto.getWaybillNo());
			dto.setWaybill(waybill);
			ActionDto action = new ActionDto();
			DestinationInfoDto destinationInfo = new DestinationInfoDto();
			switch (deliveryChangeDto.getDeliveryChangeType()) {
			case 1:
				// 网点自取
				List<SpecialHandlerDto> handlerList = new ArrayList<>();
				SpecialHandlerDto handler = new SpecialHandlerDto();
				handler.setType("32");
				handler.setCode("32005");
				handler.setOperation(deliveryChangeDto.getDeptCode() + ";" + deliveryChangeDto.getDeptAddress() + ";"
						+ deliveryChangeDto.getDeptName());
				handlerList.add(handler);
				destinationInfo.setHandlerList(handlerList);
				dto.setDestinationInfo(destinationInfo);
				action.setSpecialHandlers("32005");
				dto.setAction(action);
				break;
			case 2:
				// 更改收件人信息
				destinationInfo.setContact(deliveryChangeDto.getUserName());
				destinationInfo.setMobile(deliveryChangeDto.getMobile());
				dto.setDestinationInfo(destinationInfo);
				action.setDesitionInfoChange(true);
				dto.setAction(action);
				break;
			case 3:
				// 更改派送时间
				Date date = DateUtils.parseStrToDate(deliveryChangeDto.getDeliveryDate(), "MM/dd/yyyy");
				Date startTm = DateUtils.parseStrToDate(DateUtils.dateToStr(date, DateUtils.DATE_FORMAT_DATEONLY) + " "
						+ deliveryChangeDto.getDeliveryStartTime() + ":00");
				Date finishTm = DateUtils.parseStrToDate(DateUtils.dateToStr(date, DateUtils.DATE_FORMAT_DATEONLY) + " "
						+ deliveryChangeDto.getDeliveryEndTime() + ":00");
				dto.setExpectStartTm(startTm);
				dto.setExpectFinishTm(finishTm);
				action.setTimeChange(true);
				dto.setAction(action);
				break;
			case 7:
				List<SpecialHandlerDto> perhandlerList = new ArrayList<>();
				SpecialHandlerDto handler1 = new SpecialHandlerDto();
				handler1.setType("32");
				handler1.setCode("32009");
				StringBuffer preference = new StringBuffer();
				if (StringUtils.isNotEmpty(deliveryChangeDto.getWorkdayPreference())) {
					preference.append("0:");
					if (!deliveryChangeDto.getWorkdayPreference().contains("不派送")) {
						List<String> workPreferenceList = Arrays
								.asList(deliveryChangeDto.getWorkdayPreference().split(","));
						for (int i = 0; i < workPreferenceList.size(); i++) {
							String str = workPreferenceList.get(i);
							preference.append(str.split("-")[0].split(":")[0]+str.split("-")[0].split(":")[1]).append(str.split("-")[1].split(":")[0]+str.split("-")[1].split(":")[1]);
							if (i != workPreferenceList.size() - 1) {
								preference.append(",");
							}
						}
					}
					preference.append(";");
				}
				if (StringUtils.isNotEmpty(deliveryChangeDto.getHolidayPreference())) {
					preference.append("1:");
					if (!deliveryChangeDto.getHolidayPreference().contains("不派送")) {
						List<String> holidayPreferenceList = Arrays
								.asList(deliveryChangeDto.getHolidayPreference().split(","));
						for (int i = 0; i < holidayPreferenceList.size(); i++) {
							String str = holidayPreferenceList.get(i);
							preference.append(str.split("-")[0].split(":")[0]+str.split("-")[0].split(":")[1]).append(str.split("-")[1].split(":")[0]+str.split("-")[1].split(":")[1]);
							if (i != holidayPreferenceList.size() - 1) {
								preference.append(",");
							}
						}
					}
				}
				handler1.setOperation(preference.toString());
				perhandlerList.add(handler1);
				destinationInfo.setHandlerList(perhandlerList);
				dto.setDestinationInfo(destinationInfo);
				action.setSpecialHandlers("32009");
				dto.setAction(action);
				break;
			}
			String message = jsonCoder.object2Json(dto);
			System.out.println("kafka数据原始报文：" + message);
			KafkaData kafkaData = new KafkaData();
			kafkaData.setId(UUID.randomUUID().toString());
			kafkaData.setTopicName(KafkaConstants.DELIVERY_CHANGE_OMS_KAFKA_TOPIC);
			kafkaData.setMessage(message);
			kafkaData.setWaybillNo(deliveryChangeDto.getWaybillNo());
			kafkaData.setCreateTime(DateUtils.dateToStr(new Date()));
			kafkaDataService.addKafkaData(kafkaData);
			map.put("success", true);
		} catch (Exception e) {
			map.put("success", false);
			map.put("errorMessage", e.getMessage());
		}
		return map;
	}

	public static void main(String[] args) {
		DeliveryOmsRequestDto dto = new DeliveryOmsRequestDto();
		Random random = new Random();
		dto.setTxid(TXID_PREFIX + "033123456789" + random.nextInt(10));
		WaybillDto waybill = new WaybillDto();
		waybill.setMainNo("033123456789");
		dto.setWaybill(waybill);
		DestinationInfoDto destinationInfo = new DestinationInfoDto();
		destinationInfo.setContact("曾森苹");
		destinationInfo.setMobile("13922878356");
		dto.setDestinationInfo(destinationInfo);
		ActionDto action = new ActionDto();
		action.setDesitionInfoChange(true);
		dto.setAction(action);
		System.out.println(JSON.toJSON(dto).toString());
		System.out.println(JSON.toJSONStringWithDateFormat(dto, "yyyy-MM-dd HH:mm:ss"));
		String aa = "{\"expectFinishTm\":\"2017-07-18 13:04:00\",\"waybill\":{\"mainNo\":\"093598825604\"}}";
		DeliveryOmsRequestDto dto1 = JSON.parseObject(aa, DeliveryOmsRequestDto.class);
		System.out.println(dto1.getWaybill().getMainNo());

		//更改派件时间
		
		/*DeliveryChangeDto d = new DeliveryChangeDto();
		d.setWaybillNo("033123456789");
		d.setDeliveryChangeType(3);
		d.setDeliveryDate("07/19/2017");
		d.setDeliveryStartTime("08:00");
		d.setDeliveryEndTime("12:00");
		CustomerContoller con = new CustomerContoller();
		con.addDeliveryChange(d);*/
		
		//客户偏好
		/*DeliveryChangeDto d = new DeliveryChangeDto();
		d.setWaybillNo("033123456789");
		d.setDeliveryChangeType(7);
		d.setWorkdayPreference("08:00-12:00,12:00-18:00");
		d.setWorkdayPreference("不派送");
		d.setHolidayPreference("08:00-12:00,12:00-18:00");
		CustomerContoller con = new CustomerContoller();
		con.addDeliveryChange(d);*/
		
		//网点自取
		DeliveryChangeDto d = new DeliveryChangeDto();
		d.setWaybillNo("033123456789");
		d.setDeliveryChangeType(1);
		d.setDeptCode("755A");
		d.setDeptName("田贝网点");
		d.setDeptAddress("深圳市盐田区");
		CustomerContoller con = new CustomerContoller();
		con.addDeliveryChange(d);
	}
}
